import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

import java.util.ArrayList;

public class Storage {

	private ArrayList<String> tasks;
	private static File taskFile;
	private static final String FILE_NAME = "taskfile.txt";

	private static File openFile(String fileName) throws IOException {
		File file = null;

		try {
			file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
		} catch (IOException e) {
			System.out.println("Error in opening file");
			e.printStackTrace();
			System.exit(1);
		}
		return file;
	}

	// Constructor
	public Storage() throws IOException {
		taskFile = openFile(FILE_NAME);
		tasks = writeToTasks();
	}

	private ArrayList<String> writeToTasks() throws IOException {
		String line = null;
		ArrayList<String> tasks = null;
		try {
			tasks = new ArrayList<String>();
			BufferedReader input = new BufferedReader(new FileReader(taskFile));

			while ((line = input.readLine()) != null) {
				tasks.add(line);
			}
			input.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return tasks;
	}

	public ArrayList<String> getTasks() {
		return tasks;
	}

	public String writeToStorage(ArrayList<String> tasksList) throws IOException {
		try {
			FileWriter fw = new FileWriter(taskFile);
			BufferedWriter output = new BufferedWriter(fw);
			int size = tasksList.size();

			for (int i = 0; i < size; i++) {
				output.write(tasksList.get(i) + "\n");
			}
			output.close();
			return "saved";
		} catch (IOException e) {
			System.out.println("Error occurred in writing to storage.\n");
			e.printStackTrace();
			return "not saved";
		}
	}

}
